<?php
namespace app\api\controller;

use think\Controller;
use app\api\model\Postdatadb;
use app\erp\controller\Api;
use app\erp\model\Categorydb;
use app\erp\model\BrandApidb;
use app\erp\model\Orderdb;
use app\erp\model\Shoppingdb;
use app\erp\model\Invoicedb;
use app\erp\model\Cartdb;
use app\erp\model\Goodsdb;
use app\erp\model\Expressdb;

class Neimeng extends Controller
{

    protected $ys_config = [
        'geteway' => 'http://api.utecbj.com/erp/api/',
        'partnerId' => 25,
        'siteId' => 75,
        'appId' => 'utec',
        'appKey' => 'yserp',
        'appSecret' => 'duXtRelcYy2sJeqrLpmNvbQO0O0OO0O0O'
    ];

    protected $ys_username = 'neimeng_admin';

    protected $ys_password = '12345678';

    protected $member_id = 59;

    protected $site_url = 'http://neimeng.mall.utecbj.com';

    protected $login_url = 'http://39.104.85.103/bootshiro/';

    protected $mall_url = 'http://39.104.85.103/gpmall-interface/';

    protected $username = 'utec_0321';

    protected $password = '38022542-b161-4c6b-bbc5-b1bcf9610aca';

    protected $key = '';

    protected $access_token = '';

    public $request = array();

    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        header('Content-Type:application/json; charset=utf-8');
        defined('PARTNER_ID') or define('PARTNER_ID', $this->ys_config['partnerId']);
        defined('SITE_ID') or define('SITE_ID', $this->ys_config['siteId']);
        defined('MEMBER_ID') or define('MEMBER_ID', $this->member_id);
        $this->request = request()->param();
        if (strtolower(request()->action()) != 'getaccess') {
            $this->getAccess();
        }
    }
    // 获取用户token 3.1
    public function getAccess()
    {
        $post_data['username'] = $this->username;
        $post_data['password'] = $this->password;
        $url = $this->login_url . 'account/login';
        $data = $this->pushData($url, $post_data);
        if (! isset($data['data']['id'])) {
            exit('账号错误');
        }
        $this->key = $data['data']['id'];
        $this->access_token = $data['data']['access_token'];
    }
    // 获取区域信息 4.1
    public function getArea()
    {
        $url = $this->mall_url . 'base/getRegionList';
        $data = $this->getData($url);
        dump($data);
    }
    // 获取商品品目信息 4.2
    public function getCategory()
    {
        $url = $this->mall_url . 'goodsClass/getGoodsClass';
        if (isset($this->request['ifsupport']) && $this->request['ifsupport'] == 'true') {
            $post_data['ifsupport'] = 'true';
        } else {
            $post_data['ifsupport'] = 'false';
        }
        $post_data['pageSize'] = 1000;
        if (! isset($this->request['pageNumber'])) {
            $page_num = 1;
        } else {
            $page_num = $this->request['pageNumber'];
        }
        $post_data['pageNumber'] = $page_num;
        $data = $this->pushData($url, $post_data);
        dump($data);
    }
    // 获取品牌信息 4.3
    public function getBrand()
    {
        $url = $this->mall_url . 'goodsBrand/getGoodsBrand';
        $post_data['ifsupport'] = 'false';
        $post_data['pageSize'] = 1000;
        if (! isset($this->request['pageNumber'])) {
            $page_num = 1;
        } else {
            $page_num = $this->request['pageNumber'];
        }
        $post_data['pageNumber'] = $page_num;
        $data = $this->pushData($url, $post_data);
        dump($data);
    }
    // 添加修改商品5.1
    public function sendGoods($goods_info)
    {
        echo '推送商品：<br />';
        $url = $this->mall_url . 'goods/saveOrUpdateGoods';
        if ($goods_info['goods_api_option']) {
            if (isset($goods_info['goods_api_option']['goodsguid']) && $goods_info['goods_api_option']['goodsguid']) {
                $post_data['goodsguid'] = $goods_info['goods_api_option']['goodsguid'];
                $api_price = $goods_info['sale_price_info']['data'][0]['api_price'];
                $last_api_price = $goods_info['sale_price_info']['data'][0]['last_api_price'];
                if ($api_price != $last_api_price) {
                    $this->saleDownGoods($goods_info['goods_api_option']['goodsguid'], $goods_info);
                }
            }
        }
        $post_data['name'] = $goods_info['goods_name'];
        $post_data['code'] = $goods_info['goods_model'];
        // 获取分类
        $categorydb = new Categorydb();
        
        $get_category = $categorydb->ajaxFind($goods_info['category_sign3']);
        $post_data['goodsclassguid'] = $get_category['api_option'];
        // 获取品牌
        $brandApidb = new BrandApidb();
        $brandApidb->param['brand_sign'] = $goods_info['brand_sign'];
        $get_brand = $brandApidb->ajaxFind();
        $post_data['goodsbrandguid'] = $get_brand['option'];
        $post_data['goodscontent'] = $goods_info['goods_content'];
        $post_data['salesprice'] = $goods_info['api_price'];
        $post_data['upccode'] = '';
        $post_data['picturepath'] = $goods_info['goods_picture']['save_path'];
        $post_data['goodsparamvaluearray'] = array();
        $goods_attr = $goods_info['goods_attr'];
        foreach ($goods_attr as $key => $val) {
            if ($val['attr_value'] != '') {
                $temp['paramname'] = $val['attr_name'];
                $temp['paramvalue'] = $val['attr_value'];
                array_push($post_data['goodsparamvaluearray'], $temp);
            }
        }
        $return = $this->pushData($url, $post_data);
        echo $return['message'] . '<br />';
        $price_sign = $this->saleUpGoods($return['data']['goodsguid'], $goods_info);
        
        // $this->getGoodsDetail($return['data'],$goods_info);
        $temp_return['goodsguid'] = $return['data']['goodsguid'];
        $temp_return['price_sign'] = $price_sign;
        return $temp_return;
    }
    // 获取商品详情
    public function getGoodsDetail($api_id, $goods_info)
    {
        echo '获取商品信息<br />';
        $url = $this->mall_url . 'goods/getGoodsPrice/' . $api_id;
        $return = $this->getData($url);
        dump($return);
    }
    // 商品下架 5.2
    public function saleDownGoods($goodsguid, $goods_info)
    {
        // 商品下架后再上架
        echo '商品下架状态：<br />';
        $url = $this->mall_url . 'goods/setSales';
        $post_data['goodsguid'] = $goodsguid;
        $post_data['regionguid'] = '374001';
        $post_data['sellstatus'] = 0;
        $post_data['goodspriceguid'] = $goods_info['goods_api_option']['price_sign'];
        $return = $this->pushData($url, $post_data);
        echo $return['message'] . '<br />';
        return $return['data'];
    }

    public function saleDownGoodsDiy()
    {
        // 商品下架后再上架
        echo '商品下架状态：<br />';
        $url = $this->mall_url . 'goods/setSales';
        $post_data['goodsguid'] = '40287b996dde8368016de81f8ee40372';
        $post_data['regionguid'] = '374001';
        $post_data['sellstatus'] = 0;
        $return = $this->pushData($url, $post_data);
        echo $return['message'] . '<br />';
        return $return['data'];
    }
    // 商品上架 5.2
    public function saleUpGoods($goodsguid, $goods_info)
    {
        echo '商品上架状态：<br />';
        $url = $this->mall_url . 'goods/setSales';
        $post_data['goodsguid'] = $goodsguid;
        $post_data['regionguid'] = '374001';
        $post_data['currentprice'] = number_format($goods_info['api_price'], 2, '.', '');
        $post_data['inventory'] = 9999;
        $post_data['sellstatus'] = 1;
        // $post_data['goodspriceguid'] = md5($goods_info['goods_sku'].'_'.$post_data['regionguid']);
        $return = $this->pushData($url, $post_data);
        echo $return['message'] . '<br />';
        return $return['data'];
    }
    // 查询商品信息5.3
    public function getGoods()
    {
        echo '<br />查询商品信息：<br />';
        $url = $this->mall_url . 'goods/getGoodsList';
        $post_data['goodsclassguid'] = '52';
        $post_data['goodsstate'] = 1;
        $return = $this->pushData($url, $post_data);
        dump($return);
    }
    // 测试 创建订单
    public function createOrder()
    {
        echo '<br />创建订单：<br />';
        $url = $this->mall_url . 'orders/createOrder.do';
        $post_data = array();
        $return = $this->pushData($url, $post_data);
        dump($return);
    }
    // 获取订单信息 6.1
    public function getOrderDetail($out_order_no)
    {
        $url = $this->mall_url . 'orders/getOrderByOrderguid/' . $out_order_no;
        $return = $this->getData($url);
        if (isset($this->request['view_text'])) {
            dump($return);
        } else {
            return $return;
        }
    }
    // 获取订单信息6.2
    public function getOrderList()
    {
        echo '获取订单<br />';
        $url = $this->mall_url . 'orders/searchorderList';
        $post_data['pageNumber'] = 1;
        $post_data['pageSize'] = 100;
        $post_data['auditstatus'] = 1;
        if (isset($this->request['state'])) {
            $post_data['auditstatus'] = $this->request['state'];
        }
        
        $return = $this->pushData($url, $post_data);
        if ($return['code'] != 200) {
            echo $return['message'];
            exit();
        }
        $orderdb = new Orderdb();
        $shoppingdb = new Shoppingdb();
        $invoicedb = new Invoicedb();
        $cartdb = new Cartdb();
        $goodsdb = new Goodsdb();
        // dump($return['data']['rows']);
        foreach ($return['data']['rows'] as $key => $val) {
            $orderdb->param['out_order_no'] = $val['orderguid'];
            $orderdb->param['site_id'] = $this->ys_config['siteId'];
            $chk_order = $orderdb->ajaxFind();
            if ($chk_order != 'fail') {
                echo '订单：' . $val['orderguid'] . '已存在<br />';
                continue;
            }
            $order_data['order_no'] = $val['orderguid'];
            $order_data['out_order_no'] = $val['orderguid'];
            $order_data['api_param'] = json_encode($val);
            $order_data['order_money'] = $val['goodstotal'] * 100;
            $order_data['site_id'] = $this->ys_config['siteId'];
            $shoppingdb->param['province'] = '150000';
            $shoppingdb->param['city'] = '150100';
            $shoppingdb->param['area'] = '150101';
            $shoppingdb->param['street'] = $val['deliveryaddress'];
            $shoppingdb->param['contacts'] = $val['linkman'];
            $shoppingdb->param['phone'] = $val['linkmobile'];
            $shoppingdb->param['member_id'] = $this->member_id;
            $shoppingdb->param['is_default'] = 1;
            $get_shopping = $shoppingdb->ajaxSave();
            $order_data['shopping_id'] = $shoppingdb->last_id;
            $order_data['member_id'] = $this->member_id;
            $order_data['is_invoice'] = 2;
            // 获取发票信息
            $dates = strtotime(str_replace('T', ' ', substr('2020-11-26T02:33:42.036+0000', 0,19)));
            $order_data['create_time'] = $dates;
            $order_data['delivery_date'] = date('Y-m-d', strtotime('+ 3day', $order_data['create_time']));
            $order_data['order_member_id'] = $this->member_id;
            $cart_info = array();
            // 添加购物车
            $cartdb->param['order_no'] = '';
            foreach ($val['orderGoodsvo'] as $k => $v) {
                $goodsdb->param['site_id'] = $this->ys_config['siteId'];
                // $goodsdb->param['out_goods_sku'] = $v['goodsguid'];// 这里订单商品编号和商品编号不一致，暂时用商品名称
                $goodsdb->param['goods_name'] = $v['goodsname'];
                $goods_info = $goodsdb->ajaxApiFind();
                $cart_info[$k]['sale_attr_price_name'] = '商品价格';
                $cart_info[$k]['site_id'] = $this->ys_config['siteId'];
                $cart_info[$k]['category_sign'] = $goods_info['category_sign3'];
                $cart_info[$k]['goods_sku'] = $goods_info['goods_sku'];
                $cart_info[$k]['goods_attr_view'] = '默认属性';
                $cart_info[$k]['goods_sale_price'] = $v['finalprice'];
                $cart_info[$k]['goods_price'] = $goods_info['sale_price'];
                $cart_info[$k]['goods_market_price'] = $goods_info['market_price'];
                $cart_info[$k]['num'] = $v['qty'];
                $cart_info[$k]['create_time'] = $order_data['create_time'];
                $cart_info[$k]['member_id'] = $this->member_id;
                $cart_info[$k]['sale_attr'] = '';
                $cart_info[$k]['sale_attr_html'] = '';
            }
            $cartdb->param['cart_info'] = $cart_info;
            $cartdb->addCart();
            $order_data['cart_ids'] = $cartdb->inset_ids;
            $order_data['invoice_type'] = 1;
            $order_data['invoice_title'] = $val['ordersInvoice']['title'];
            $order_data['invoice_duty'] = $val['ordersInvoice']['code'];
            $order_data['invoice_tel'] = '';
            $order_data['invoice_addr'] = $val['ordersInvoice']['address'];
            $order_data['invoice_bank'] = $val['ordersInvoice']['bankname'];
            $order_data['invoice_account'] = $val['ordersInvoice']['bankaccount'];
            $order_data['member_id'] = $this->member_id;
            $order_data['invoice_money'] = $order_data['order_money'];
            $order_data['cart_ids'] = $cartdb->inset_ids;
            $order_data['order_nos'] = $orderdb->last_order_no;
            $order_data['site_id'] = $this->ys_config['siteId'];
            $orderdb->param = $order_data;
            $orderdb->addOrder();
            echo '订单：' . $order_data['order_no'] . '录入成功<br />';
        }
    }
    // 修改订单状态 6.3
    public function setOrder($order_no)
    {
        echo '设置订单状态';
        $orderdb = new Orderdb();
        $orderdb->param['order_no'] = $order_no;
        $get_order = $orderdb->ajaxFind();
        $get_order_detail = $this->getOrderDetail($get_order['out_order_no']);
        $url = $this->mall_url . 'orders/confirmOrder';
        $post_data['orderguid'] = $get_order['out_order_no'];
        $post_data['auditstatus'] = $get_order['order_state']; // 确定订单 2 发货 3 4 已收货 1已取消 -2退回
        if ($get_order['order_state'] == 3) {
            $post_data['logisticsList'] = array(); // 发货时信息
            $expressdb = new Expressdb();
            $expressdb->param['order_no'] = $order_no;
            $get_express = $expressdb->ajaxList();
            foreach ($get_express as $k => $v) {
                foreach ($v['cart_list'] as $key => $val) {
                    foreach ($get_order_detail['data']['orderGoodsvo'] as $a => $b) {
                        if ($b['goodsname'] == $val['goods_info']['goods_name']) {
                            $temp['ordergoodsguid'] = $b['ordergoodsguid'];
                            $temp['logisticstype'] = 1;
                            $temp['logisticscode'] = $v['express_no'];
                            $temp['logisticsname'] = '优士创新';
                            array_push($post_data['logisticsList'], $temp);
                        }
                    }
                }
            }
        }
        
        $return = $this->pushData($url, $post_data);
        return $return;
    }
    // 取消订单 6.4
    public function channelOrder($out_order_no)
    {
        echo '取消订单：';
        $url = $this->mall_url . 'orders/sendBacktoOrder';
        $post_data['orderguid'] = $out_order_no;
        $post_data['auditstatus'] = - 2; // 取消订单
        $post_data['content'] = '取消订单'; // 发货时信息
        $return = $this->pushData($url, $post_data);
        return $return;
    }
    // 修改物流信息 6.5 收货的时候用到
    public function setLogistics($express_info)
    {
        echo '修改物流信息';
        $url = $this->mall_url . 'orders/saveOrUpdateLogistics';
        $post_data['orderguid'] = $express_info['order_info']['out_order_no'];
        $post_data['logisticsList'] = array();
        foreach ($express_info as $key => $val) {
            $temp['ordergoodsguid'] = $val['express_no'];
            $temp['logisticstype'] = '自配物流';
            $temp['logisticscode'] = $val['express_id'];
            $temp['logisticsname'] = '优势创新';
            $temp['remark'] = '已收货';
            array_push($post_data, $temp);
        }
        $return = $this->pushData($url, $post_data);
        dump($return);
    }
    // 创建结算单 7.1 订单收货
    public function createSettlement($order_info)
    {
        $api_param = json_decode($order_info['api_param'], true);
        echo '创建结算单:';
        $url = $this->mall_url . 'settlement/createSettlement';
        $post_data['orderIds'] = $order_info['out_order_no'];
        $post_data['settlementname'] = $api_param['orgname']; // 结算单位名称
        $post_data['remark'] = '';
        $return = $this->pushData($url, $post_data);
        return $return;
    }
    // 结算单列表 7.2
    public function settlementList()
    {
        echo '结算单:';
        $url = $this->mall_url . 'settlement/searchSettlement';
        $post_data['pageNumber'] = 1;
        $return = $this->pushData($url, $post_data);
        return $return;
    }
    // 修改结算单状态 7.3 （目前感觉是收款状态）
    public function setSettlement($order_info)
    {
        echo '修改结算单：';
        $url = $this->mall_url . 'settlement/updateSettlementById';
        $post_data['orderIds'] = $order_info['out_order_no'];
        $post_data['state'] = 1; // 暂时不知道结算单值
        $return = $this->pushData($url, $post_data);
        dump($return);
    }
    // 创建合同 8.1 (订单确认之后应该有合同)
    public function createContract($out_order_no)
    {
        $url = $this->mall_url . 'contract/createContract/' . $out_order_no;
        $return = $this->getData($url);
        dump($return);
        // return $return; // 这里应该有合同标识
    }
    // 发送合同8.2 创建之后就可发送
    public function sendContract($contract_id)
    {
        echo '发送合同：';
        $url = $this->mall_url . 'contract/sendContract/' . $contract_id;
        $return = $this->getData($url);
    }
    // 合同详情 8.3
    public function contractDetail($contract_id)
    {
        echo '合同详情：';
        $url = $this->mall_url . 'contract/getContract/' . $contract_id;
        $return = $this->getData($url);
        dump($return); // 这里应该有合同标识
    }
    // 查询合同列表 8.4
    public function contractList()
    {
        $url = $this->mall_url . 'contract/getContractList';
        $post_data['pageNumber'] = 1;
        $return = $this->pushData($url, $post_data);
        dump($return);
    }

    protected function getData($url)
    {
        $ch = curl_init();
        if (strtolower(request()->action()) != 'getaccess') {
            $headers = array(
                "Content-type: application/json;charset='utf-8'",
                "id:" . $this->key,
                "access_token:" . $this->access_token
            );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $json_data = json_decode($result, true);
        if (isset($json_data['status']) && $json_data['status']) {
            dump($json_data);
            exit('服务器错误');
        }
        return json_decode($result, true);
    }

    protected function pushData($url, $post_data)
    {
        $ch = curl_init();
        $json_data = json_encode($post_data);
        $postdatadb = new Postdatadb();
        $postdatadb->param['post_json'] = json_decode($json_data, true);
        $postdatadb->param['post_url'] = $url;
        $postdatadb->ajaxSave();
        if (strtolower(request()->action()) != 'getaccess') {
            $headers = array(
                "Content-type: application/json;charset='utf-8'",
                "id:" . $this->key,
                "access_token:" . $this->access_token
            );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $json_data = json_decode($result, true);
        if (isset($json_data['status']) && $json_data['status']) {
            dump($json_data);
            exit('服务器错误');
        }
        return json_decode($result, true);
    }

    protected function sendInfo($string_uri, $post)
    {
        $post['config'] = $this->ys_config;
        $json_data = json_encode($post);
        $postdatadb = new Postdatadb();
        $postdatadb->param['post_json'] = json_decode($json_data, true);
        $postdatadb->param['post_url'] = $string_uri;
        $postdatadb->ajaxSave();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->ys_config['geteway'] . $string_uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-type: application/json;charset='utf-8'"
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        $json_data = json_decode($result, true);
        if (isset($json_data['status']) && $json_data['status']) {
            dump($json_data);
            exit('服务器错误');
        }
        return json_decode($result, true);
    }
}